import { readFileSync, writeFileSync } from 'fs'
import { resolve } from 'path'
import { ITodoData } from '../src/js/typing'
import { ITodoItem } from './typing'

export const UReadFileSync = (path: string) => {
    const fileData = readFileSync(resolve(__dirname, path), 'utf8')
    return fileData === '' ? [] : JSON.parse(fileData)
}

export const UWriteFileSync = <T>(path: string, data: T): void => {
    writeFileSync(resolve(__dirname, path), JSON.stringify(data))
}

export const fileOperation = (path: string, fn?: any) => {
    const fileData = UReadFileSync(path)
    fileData.forEach((item: any) => {
        item.complete = item.complete == 'true'
    });
    if (!fn) {
        return fileData
    }
    const newData = fn(fileData)
    if (newData?.length > 0) {

        UWriteFileSync(path, newData)
    }

}